// pages/index1/index1.js
console.log('Page object available:', typeof Page !== 'undefined');

const app = getApp();
const baseUrl = app.getApiBaseUrl();

Page({
  data: {
    message: 'Hello, Index1!',
    chatInput: '',
    showHintPopup: false,
    userRole: '',
    isLoading: true,
    isLoggedIn: false
  },

  onLoad() {
    console.log('Index1 Page Loaded');
    this.attemptLogin();
  },

  onShow() {
    this.attemptLogin();
  },

  handleLoginSuccess(res) {
    const unionID = res.unionID || '';
    const userRole = res.role || 'lifelong_learner';
    console.log('index2 handleLoginSuccess: unionID:', unionID, 'userRole:', userRole);
    this.setData({
      userRole,
      isLoggedIn: !!unionID
    });
  },

  attemptLogin() {
    const app = getApp();
    this.setData({ isLoading: true });
    if (app.globalData.isLoggingIn) {
      app.globalData.loginPromise.then((res) => {
        this.handleLoginSuccess(res);
        this.setData({ isLoading: false });
      }).catch((err) => {
        this.handleLoginFailure(err);
        this.setData({ isLoading: false });
      });
    } else {
      app.ensureValidToken().then((res) => {
        this.handleLoginSuccess(res);
        this.setData({ isLoading: false });
      }).catch((err) => {
        this.handleLoginFailure(err);
        this.setData({ isLoading: false });
      });
    }
  },

  handleLoginFailure(err) {
    console.error('index2 handleLoginFailure: 获取 token 失败:', err);
    this.setData({
      isLoggedIn: false
    });
    wx.showToast({ title: '登录失败，请稍后重试', icon: 'none', duration: 2000 });
  },

  retryLogin() {
    const app = getApp();
    this.setData({ isLoading: true });
    app.doAutoLogin(true).then((res) => {
      this.handleLoginSuccess(res);
      this.setData({ isLoading: false });
    }).catch((err) => {
      this.handleLoginFailure(err);
      this.setData({ isLoading: false });
    });
  },

  goToExpertPath(e) {
    const pathID = e.currentTarget.dataset.pathId;
    if (!pathID) {
      wx.showToast({ title: '路径ID未定义', icon: 'none' });
      return;
    }

    const unionID = wx.getStorageSync('unionID');
    if (!unionID) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }

    wx.navigateTo({
      url: `/pages/expertPath/expertConversation/expertConversation?pathID=${pathID}`,
      success: () => console.log(`跳转到专家路径对话成功，pathID: ${pathID}`),
      fail: (err) => {
        console.error('跳转失败:', err);
        wx.showToast({ title: '跳转失败，请重试', icon: 'none' });
      }
    });
  },

  goToMore(e) {
    const kind = e.currentTarget.dataset.kind;
    wx.navigateTo({
      url: `/pages/index_more/index_more?kind=${kind}`,
      success: () => console.log(`跳转到 index_more 页面成功，kind: ${kind}`),
      fail: (err) => console.error('跳转失败:', err)
    });
  },

  handleInput(e) {
    this.setData({
      chatInput: e.detail.value
    });
  },

  sanitizeTitle(title) {
    if (!title) return '';
    const allowedPattern = /[\w\s.,!?()\u4e00-\u9fff]/g;
    const cleaned = (title.match(allowedPattern) || []).join('');
    const maxLength = 100;
    if (cleaned.length > maxLength) {
      return cleaned.substring(0, maxLength);
    }
    return cleaned;
  },

  sendChat(e) {
    let question = this.data.chatInput.trim();
    console.log('用户输入的问题:', question);
    if (!question) {
      wx.showToast({ title: '请输入问题', icon: 'none' });
      return;
    }

    question = this.sanitizeTitle(question);
    if (!question) {
      wx.showToast({ title: '输入包含非法字符，请重新输入', icon: 'none' });
      return;
    }

    wx.setStorageSync('chatQuestion', question);
    this.setData({ chatInput: '' });

    const unionID = wx.getStorageSync('unionID');
    if (!unionID) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }

    wx.showLoading({ title: '检查中...' });
    wx.request({
      url: `${baseUrl}/conversation/check_similarity`,
      method: 'POST',
      data: {
        unionID: unionID,
        question: question
      },
      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${wx.getStorageSync('jwt_token')}`
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.success) {
          if (res.data.conversationID) {
            wx.hideLoading();
            wx.setStorageSync('selectedConversationID', res.data.conversationID);
            wx.switchTab({
              url: '/pages/conversation/conversation',
              success: () => console.log('跳转到已有对话成功'),
              fail: (err) => console.error('跳转失败:', err)
            });
          } else {
            this.createNewConversation(unionID, question);
          }
        } else {
          wx.hideLoading();
          wx.showToast({ title: '检查失败，请重试', icon: 'none' });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('检查相似性失败:', err);
        wx.showToast({ title: '网络错误', icon: 'none' });
        this.createNewConversation(unionID, question);
      }
    });
  },

  createNewConversation(unionID, question) {
    wx.showLoading({ title: '创建对话中...' });
    wx.request({
      url: `${baseUrl}/conversation/add`,
      method: 'POST',
      data: {
        unionID: unionID,
        title: question
      },
      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${wx.getStorageSync('jwt_token')}`
      },
      success: (res) => {
        wx.hideLoading();
        if (res.statusCode === 200 && res.data.success && res.data.conversationID) {
          wx.setStorageSync('selectedConversationID', res.data.conversationID);
          wx.switchTab({
            url: '/pages/conversation/conversation',
            success: () => console.log('跳转成功'),
            fail: (err) => console.error('跳转失败:', err)
          });
        } else if (res.statusCode === 422 && res.data.detail?.errorCode === 'INPUT_NOT_LEARNING_RELATED') {
          this.setData({ showHintPopup: true });
        } else if (res.statusCode === 400 && res.data.detail) {
          wx.showToast({ title: res.data.detail || '输入包含非法字符', icon: 'none' });
        } else {
          wx.showToast({ title: res.data?.message || '创建失败', icon: 'none' });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('创建对话失败:', err);
        wx.showToast({ title: '网络错误', icon: 'none' });
      }
    });
  },

  hideHintPopup() {
    this.setData({ showHintPopup: false });
  },

  stopPropagation() {},

  getSubjectDisplay(subject) {
    const subjectMap = {
      'english': '英语',
      'math': '数学',
      'physics': '物理',
      'chemistry': '化学',
      'biology': '生物',
      'history': '历史',
      'politics': '政治',
      'geography': '地理',
      'chinese': '语文',
      'vocational_it': '信息技术',
      'vocational_finance': '金融与会计',
      'higher_computer_science': '计算机科学',
      'higher_engineering': '工程学',
      'professional_cpa': '注册会计师',
      'professional_legal': '法律职业资格',
      'lifelong_learning_language': '语言学习',
      'lifelong_learning_programming': '编程入门',
      'general': '通用'
    };
    let level = '';
    let sub = (subject || 'general').toLowerCase();
    if (sub.startsWith('zk_')) {
      level = '初中';
      sub = sub.replace('zk_', '');
    } else if (sub.startsWith('gk_')) {
      level = '高中';
      sub = sub.replace('gk_', '');
    } else if (sub.startsWith('vocational_')) {
      level = '职业';
      sub = sub.replace('vocational_', '');
    } else if (sub.startsWith('higher_')) {
      level = '高等';
      sub = sub.replace('higher_', '');
    } else if (sub.startsWith('professional_')) {
      level = '从业';
      sub = sub.replace('professional_', '');
    } else if (sub.startsWith('lifelong_learning_')) {
      level = '终身';
      sub = sub.replace('lifelong_learning_', '');
    }
    const subjectName = subjectMap[sub] || '';
    return level ? `${level}${subjectName}` : subjectName;
  },

  getCategoryLabel(subject) {
    if (subject.includes('zk')) return '初中';
    if (subject.includes('gk')) return '高中';
    if (subject.includes('vocational')) return '职业教育';
    if (subject.includes('higher')) return '高等教育';
    if (subject.includes('professional')) return '从业资格';
    if (subject.includes('lifelong')) return '终身学习';
    return '通用';
  },

  getCategoryClass(subject) {
    if (subject.includes('zk') || subject.includes('gk')) return 'academic';
    if (subject.includes('vocational')) return 'vocational';
    if (subject.includes('higher')) return 'higher';
    if (subject.includes('professional')) return 'professional';
    if (subject.includes('lifelong')) return 'lifelong';
    return 'general';
  },
  
  // 转发，图片长宽比是 5:4
  onShareAppMessage() {
    const unionID = wx.getStorageSync('unionID') || '';
    const sharePath = unionID 
      ? `/pages/index1/index1?inviterID=${encodeURIComponent(unionID)}`
      : '/pages/index1/index1';
    
    wx.showShareMenu({
      menus: ['shareAppMessage', 'shareTimeline']
    });
    
    return {
      title: '有约学习导航',
      path: sharePath
    };
  },

  // 分享到朋友圈
  onShareTimeline() {
    const unionID = wx.getStorageSync('unionID') || '';
    const query = unionID ? `inviterID=${encodeURIComponent(unionID)}` : '';
    
    return {
      title: '有约学习导航',
      query: query
    };
  }
});